<template>
  <div class="edit-user-form">
    <h2>编辑用户（使用 axios.request）</h2>

    <div v-if="successMessage" class="success">{{ successMessage }}</div>

    <form @submit.prevent="updateUser">
      <div class="form-group">
        <label>用户ID：</label>
        <input v-model.number="user.id" type="number" required/>
      </div>

      <div class="form-group">
        <label>用户名：</label>
        <input v-model="user.name" type="text" required/>
      </div>


      <button type="submit" :disabled="loading">
        {{ loading ? '提交中...' : '更新用户' }}
      </button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {
        id: '',
        name: '',
      },
      loading: false,
      successMessage: '',
    };
  },
  methods: {
    updateUser() {
      this.loading = true;

      axios.request({
        method: 'put',
        url: `https://jsonplaceholder.typicode.com/users/${this.user.id}`,
        data: this.user
      }).then(response => {
        this.successMessage = '更新成功！' + JSON.stringify(response.data);
      }).catch(error => {
        alert('更新失败');
        console.error(error);
      }).finally(() => {
        this.loading = false;
      });

      // 下面这句会立刻执行，不会被 await 阻塞
      console.log('PUT 请求已发出，继续执行其它逻辑...');
    },
  },
};
</script>

<style scoped>
.edit-user-form {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 15px;
}

input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
}

button {
  padding: 10px 15px;
  background-color: #2c3e50;
  color: white;
  border: none;
  cursor: pointer;
}

button:disabled {
  background-color: #aaa;
}

.success {
  color: green;
  margin-bottom: 15px;
}
</style>